package cn.iocoder.yudao.module.book.service.posts;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.book.controller.admin.posts.vo.*;
import cn.iocoder.yudao.module.book.dal.dataobject.posts.PostsDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.book.dal.mysql.posts.PostsMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.book.enums.ErrorCodeConstants.*;

/**
 * 社区动态 Service 实现类
 *
 * @author ding
 */
@Service
@Validated
public class PostsServiceImpl implements PostsService {

    @Resource
    private PostsMapper postsMapper;

    @Override
    public Long createPosts(PostsSaveReqVO createReqVO) {
        // 插入
        PostsDO posts = BeanUtils.toBean(createReqVO, PostsDO.class);
        postsMapper.insert(posts);
        // 返回
        return posts.getPostId();
    }

    @Override
    public void updatePosts(PostsSaveReqVO updateReqVO) {
        // 校验存在
        validatePostsExists(updateReqVO.getPostId());
        // 更新
        PostsDO updateObj = BeanUtils.toBean(updateReqVO, PostsDO.class);
        postsMapper.updateById(updateObj);
    }

    @Override
    public void deletePosts(Long id) {
        // 校验存在
        validatePostsExists(id);
        // 删除
        postsMapper.deleteById(id);
    }

    private void validatePostsExists(Long id) {
        if (postsMapper.selectById(id) == null) {
            throw exception(POSTS_NOT_EXISTS);
        }
    }

    @Override
    public PostsDO getPosts(Long id) {
        return postsMapper.selectById(id);
    }

    @Override
    public PageResult<PostsDO> getPostsPage(PostsPageReqVO pageReqVO) {
        return postsMapper.selectPage(pageReqVO);
    }

}